<?php

namespace app\merchant_staff\controller\billiard;

use addons\mycurrency\library\Common;
use app\common\controller\MerchantStaff;
use app\common\library\device\cabinet\Analysis;
use app\common\library\device\cabinet\Control;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\mycurrency\DeviceInstruction;
use app\common\model\mycurrency\DeviceLattice;
use app\common\model\mycurrency\MerchantStore;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Queue;
use think\Validate;
use app\common\model\mycurrency\MerchantStaff as StaffMoney;
use app\common\model\mycurrency\Agent;

/**
 * 设备接口
 */
class Device extends MerchantStaff
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
    }

    /**
     * 扫码绑定设备
    */
    public function deviceBinding(){
        $params = $this->request->param();
        $rule = [
            ['number', 'require', '设备编号不能为空'],
            ['title', 'require', '设备名称不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($this->identity != 2){
            $this->error('非门店账号不能绑定设备');
        }
        $device = \app\common\model\mycurrency\Device::where(['number' => $params['number'],'deletetime' => null])->find();
        if(!$device){
            $this->error('设备不存在');
        }
        if($device->store_id != null){
            if($device->store_id == $this->store_id){
                $this->error('设备已绑定，请勿重复绑定');
            }else{
                $this->error('设备已被其他门店绑定');
            }
        }
        $device->store_id = $this->store_id;
        $device->title = $params['title'];
        $device->save();
        $this->success('绑定成功');
    }


    /**
     * 设备列表
     */
    public function deviceList(){

        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $store_ids = null;
        if ($this->identity == 1){//代理商、业务员
            if($this->agent['role_type'] == Agent::ROLE_TYPE_DAILI){//是区域代理
                $agent_ids = Agent::where(['pid' => $this->agent_id,'role_type' => Agent::ROLE_TYPE_YEWUYUAN,'deletetime' => null])->column('id');
                $agent_ids[] = $this->agent_id;
            }elseif ($this->agent['role_type'] == Agent::ROLE_TYPE_YEWUYUAN){//是业务员
                $agent_ids = [$this->agent_id];
            }
            $store_ids = MerchantStore::where(['agent_id' => ['in',$agent_ids],'deletetime' => null])->column('id');
        }elseif ($this->identity == 2){
            $store_ids = $this->store_id;
        }
        $where = [
            'store_id' => ['in',$store_ids],
            'deletetime' => null,
        ];
        $list = \app\common\model\mycurrency\Device::with(['store' =>function($query){
                $query->field('id,store_name,status,dorrhead_image,management_type');
            }])
            ->where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        $num = \app\common\model\mycurrency\Device::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);


    }

    /**
     * 设备编辑
     */
    public function deviceUpdate(){

    }

    /**
     * 设备解绑
     */
    public function deviceUnbind(){
        $params = $this->request->param();
        $rule = [
            ['device_id', 'require', '设备id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($this->identity != 2){
            $this->error('非门店账号不能绑定设备');
        }
        $device = \app\common\model\mycurrency\Device::where(['id' => $params['device_id'],'deletetime' => null])->find();
        if(!$device){
            $this->error('设备不存在');
        }
        if($device->store_id != $device->store_id){
            $this->error('您未绑定该设备');
        }
        $device->store_id = null;
        $device->save();
        $this->success('解绑成功');
    }

    /**
     * 设备格口列表
     */
    public function deviceLatticeList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
            ['device_id', 'require', '设备id不能为空'],

        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $where = [
            'device_id' => $params['device_id'],
            'deletetime' => null,
        ];
        $list = DeviceLattice::with(['storeGoods' =>function($query){
                $query->with(['goods' =>function($query){
                    $query->field('id,title,abbreviation_image');
                },'strategy' => function($query){
                    $query->field('id,title,duration,unit_price,types');
                }]);
            }])
            ->where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('number asc')
            ->field('*')
            ->select();
        foreach ($list as $k => $v){
            if($list[$k]['store_goods'] != null){
                $list[$k]['store_goods']['goods']['abbreviation_imagea'] = Common::GetHost() . $list[$k]['store_goods']['goods']['abbreviation_image'];
            }
            $list[$k]['infrared_time'] = $list[$k]['infrared_time'] == '' ? '' : date('H:i:s',$list[$k]['infrared_time']);
            $list[$k]['block_time'] = $list[$k]['block_time'] == '' ? '' : date('H:i:s',$list[$k]['block_time']);
            $list[$k]['door_time'] = $list[$k]['door_time'] == '' ? '' : date('H:i:s',$list[$k]['door_time']);
        }
        $num = DeviceLattice::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }

    /**
     * 设备格口编辑 - 门店产品列表
     */
    public function storeGoods(){
//        if($this->identity != 2){
//            $this->error('非门店账号不能绑定设备');
//        }
        $params = $this->request->param();
        if(array_key_exists('device_id',$params)){
            $store_id = \app\common\model\mycurrency\Device::where(['id' => $params['device_id']])->value('store_id');
        }else{
            $store_id = $this->store_id;
        }
        $where = [
            'store_id' => $store_id,
            'deletetime' => null,
        ];
        $list = \app\common\model\billiard\StoreGoods::with(['goods'=>function($query){
                $query->field('id,title');
            }])
            ->where($where)
            ->order('id desc')
            ->field('id,goods_id')
            ->select();
        $data = [];
        foreach($list as $k => $v){
            $data[] = [
                'id' => $v['id'],
                'title' => $v['goods']['title'],
            ];
        }
        $this->success('获取成功', ['list' => $data]);
    }

    /**
     * 设备格口编辑
     */
    public function deviceLatticeUpdate(){
        $params = $this->request->param();
        $rule = [
            ['store_goods_id', 'require', '门店产品id不能为空'],
            ['status', 'require', '格口状态不能为空'],
            ['device_lattice_id', 'require', '格口id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $lattice = DeviceLattice::where(['id' => $params['device_lattice_id'],'deletetime' => null])->find();
        if (!$lattice){
            $this->error('格口不存在');
        }
        $lattice->store_goods_id = $params['store_goods_id'];
        $lattice->status = $params['status'];
        $lattice->save();
        $this->success('编辑成功');
    }

    /**
     * 设备操作
    */
    public function deviceOperate(){
        $params = $this->request->param();
        $codeAll = [
            Analysis::CODE_KAIMEN,//开门
            Analysis::CODE_CHAXUNZHUANGTAI,//查询柜门状态
            //Analysis::CODE_KAIDENG,//开关灯
        ];
        $codein = implode(',',$codeAll);
        $rule = [
            ['code', "require|in:{$codein}", '指令不能为空|指令类型错误'],
            ['lattice_id', 'require|number', '柜门id不能为空|柜门id必须为数字'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        if($params['code'] == Analysis::CODE_KAIDENG){//如果是开关灯
            $rule = [
                ['pattern', "require|in:0,1,2", '模式不能为空|模式类型错误'],
                ['delayed', 'require', '延时时长不能为空'],
            ];
            $check = $this->validate($params, $rule);
            if ($check !== true) {
                $this->error($check);
            }
        }
        $lattice = DeviceLattice::where(['id' => $params['lattice_id'],'deletetime' => null])->find();
        if(!$lattice){
            $this->error('柜门不存在或已被删除');
        }
        try {
            $result = \app\common\model\mycurrency\Device::operateDevice(
                (int)$params['code'],
                $params['lattice_id'],
                [
                    'pattern' => $params['pattern'] ?? null,
                    'delayed' => $params['delayed'] ?? null
                ]
            );
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('控制成功');
    }

    /**
     * 设备操作 - 读取红外感应状态 及 卡ID
    */
    public function sensorBlockRead(){
        $params = $this->request->param();
        $rule = [
            ['device_id', 'require', '设备id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $device = \app\common\model\mycurrency\Device::where(['id' => $params['device_id']])->find();
        $device_lattice = DeviceLattice::where(['device_id' => $device->id,'deletetime' => null])->order('number asc')->find();
        $data = '0';
        Control::sending($device->id,Analysis::CODE_CHAXUNCHUANGANQI,$data,[
            'control_type' => DeviceInstruction::CONTROL_TYPE_GUANLIYUANCHAXUNHONGWAIZHEDANGQINGKUANG,
        ]);
        //Control::sending($device->id,Analysis::CODE_BUKA,"{$device_lattice['number']}",[
        //    'device_lattice_id' => $device_lattice->id,//柜门id
        //    'control_type' => DeviceInstruction::CONTROL_TYPE_DULICHAXUN,
        //]);
        $queue_default = config('queue.default');
        Queue::later(10, "app\common\job\Device@obtainNfcId", [
            'device_id' => $device->id,
            'device_lattice_id' => $device_lattice->id
        ], $queue_default);
//        $lattice = DeviceLattice::where(['device_id' => $params['device_id'],'deletetime' => null])->select();
//        foreach($lattice as $k => $v){
//            Control::sending($device->id,Analysis::CODE_CHAXUNZHUANGTAI,$v['number'],[
//                'device_lattice_id' => $v['id'],
//                'control_type' => DeviceInstruction::CONTROL_TYPE_GUIMENKAIGUANZHUANGTAI,
//            ]);
//        }
        $this->success('控制成功');
    }




}
